package com.boot.stomp;

import com.boot.security.model.vo.AccountInfo;
import com.boot.security.service.authentication.TokenService;
import com.boot.stomp.authentication.StompAuthenticationHandler;
import com.sun.security.auth.UserPrincipal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;

import java.security.Principal;

@Slf4j
public class TokenAuthenticationHandler implements StompAuthenticationHandler {

    private final TokenService tokenService;

    public TokenAuthenticationHandler(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public Principal getPrincipal(StompHeaderAccessor accessor) {
        String token = accessor.getFirstNativeHeader(TokenService.AUTHORIZATION);
        Claims claims = tokenService.parse(token);
        // Token 是否过期
        if (tokenService.isNotExpired(claims)) {
            // Token 是否需要更新
            AccountInfo info = tokenService.getAccountInfo(claims);
            return new UserPrincipal(info.getUsername());
        } else {
            log.info("{} 的Token 已经过期", claims.getSubject());
            return null;
        }
    }
}
